<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="第25篇：单元测试, 张亚飞,飞凡空间,国学,Python,Go">
    <meta name="description" content="一、如何写好单元测试单元测试(Unit Tests, UT) 是一个优秀项目不可或缺的一部分，特别是在一些频繁变动和多人合作开发的项目中尤为重要。你或多或少都会有因为自己的提交，导致应用挂掉或服务宕机的经历。如果这个时候你的修改导致测试用例">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
	<meta name="baidu-site-verification" content="code-w2ezfaoXE0" />
    <title>第25篇：单元测试 | 飞凡空间</title>
    <link rel="icon" type="image/png" href="/medias/my-logo.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    
    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 5.2.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="飞凡空间" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css">
<link rel="stylesheet" href="/css/prism-line-numbers.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/my-logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">飞凡空间</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/my-logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">飞凡空间</div>
        <div class="logo-desc">
            
            诚者，天之道也；诚之者，人之道也。诚者，不勉而中，不思而得。从容中道，圣人也；诚之者，择善而固执者也。
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Go/blog/25.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        第25篇：单元测试
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Go%E4%B9%8B%E8%B7%AF/">
                                <span class="chip bg-color">Go之路</span>
                            </a>
                        
                            <a href="/tags/%E5%8D%95%E5%85%83%E6%B5%8B%E8%AF%95/">
                                <span class="chip bg-color">单元测试</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Go/" class="post-category">
                                Go
                            </a>
                        
                            <a href="/categories/Go/base/" class="post-category">
                                base
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-01-08
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    7.5k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    32 分
                </div>
                
				
                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
            
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h2 id="一、如何写好单元测试"><a href="#一、如何写好单元测试" class="headerlink" title="一、如何写好单元测试"></a>一、如何写好单元测试</h2><p>单元测试(Unit Tests, UT) 是一个优秀项目不可或缺的一部分，特别是在一些频繁变动和多人合作开发的项目中尤为重要。你或多或少都会有因为自己的提交，导致应用挂掉或服务宕机的经历。如果这个时候你的修改导致测试用例失败，你再重新审视自己的修改，发现之前的修改还有一些特殊场景没有包含，恭喜你减少了一次上库失误。也会有这样的情况，项目很大，启动环境很复杂，你优化了一个函数的性能，或是添加了某个新的特性，如果部署在正式环境上之后再进行测试，成本太高。对于这种场景，几个小小的测试用例或许就能够覆盖大部分的测试场景。而且在开发过程中，效率最高的莫过于所见即所得了，单元测试也能够帮助你做到这一点，试想一下，假如你一口气写完一千行代码，debug 的过程也不会轻松，如果在这个过程中，对于一些逻辑较为复杂的函数，同时添加一些测试用例，即时确保正确性，最后集成的时候，会是另外一番体验。</p>
<p>如何写好单元测试呢？</p>
<p>首先，学会写测试用例。比如如何测试单个函数/方法；比如如何做基准测试；比如如何写出简洁精炼的测试代码；再比如遇到数据库访问等的方法调用时，如何 <code>mock</code>。</p>
<p>然后，写可测试的代码。<code>高内聚，低耦合</code>是软件工程的原则，同样，对测试而言，函数/方法写法不同，测试难度也是不一样的。职责单一，参数类型简单，与其他函数耦合度低的函数往往更容易测试。我们经常会说，“这种代码没法测试”，这种时候，就得思考函数的写法可不可以改得更好一些。为了代码可测试而重构是值得的。</p>
<p>接下来将介绍如何使用 Go 语言的标准库 <code>testing</code> 进行单元测试。</p>
<h2 id="二、一个简单例子"><a href="#二、一个简单例子" class="headerlink" title="二、一个简单例子"></a>二、一个简单例子</h2><p>Go 语言推荐测试文件和源代码文件放在一块，测试文件以 <code>_test.go</code> 结尾。比如，当前 package 有 <code>calc.go</code> 一个文件，我们想测试 <code>calc.go</code> 中的 <code>Add</code> 和 <code>Mul</code> 函数，那么应该新建 <code>calc_test.go</code> 作为测试文件。</p>
<pre><code>example/
   |--calc.go
   |--calc_test.go</code></pre>
<p>假如 <code>calc.go</code> 的代码如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">func</span> <span class="token function">Add</span><span class="token punctuation">(</span>a <span class="token builtin">int</span><span class="token punctuation">,</span> b <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> a <span class="token operator">+</span> b
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">Mul</span><span class="token punctuation">(</span>a <span class="token builtin">int</span><span class="token punctuation">,</span> b <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> a <span class="token operator">*</span> b
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>那么 <code>calc_test.go</code> 中的测试用例可以这么写：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token string">"testing"</span>

<span class="token keyword">func</span> <span class="token function">TestAdd</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> ans <span class="token operator">:=</span> <span class="token function">Add</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">;</span> ans <span class="token operator">!=</span> <span class="token number">3</span> <span class="token punctuation">{</span>
        t<span class="token punctuation">.</span><span class="token function">Errorf</span><span class="token punctuation">(</span><span class="token string">"1 + 2 expected be 3, but %d got"</span><span class="token punctuation">,</span> ans<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">if</span> ans <span class="token operator">:=</span> <span class="token function">Add</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">20</span><span class="token punctuation">)</span><span class="token punctuation">;</span> ans <span class="token operator">!=</span> <span class="token operator">-</span><span class="token number">30</span> <span class="token punctuation">{</span>
        t<span class="token punctuation">.</span><span class="token function">Errorf</span><span class="token punctuation">(</span><span class="token string">"-10 + -20 expected be -30, but %d got"</span><span class="token punctuation">,</span> ans<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>测试用例名称一般命名为 <code>Test</code> 加上待测试的方法名。</li>
<li>测试用的参数有且只有一个，在这里是 <code>t *testing.T</code>。</li>
<li>基准测试(benchmark)的参数是 <code>*testing.B</code>，<code>TestMain</code> 的参数是 <code>*testing.M</code> 类型。</li>
</ul>
<p>运行 <code>go test</code>，该 package 下所有的测试用例都会被执行。</p>
<pre class="line-numbers language-shell"><code class="language-shell">$ go test
ok      example 0.009s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>
<p>或 <code>go test -v</code>，<code>-v</code> 参数会显示每个用例的测试结果，另外 <code>-cover</code> 参数可以查看覆盖率。</p>
<pre class="line-numbers language-sh"><code class="language-sh">$ go test -v
=== RUN   TestAdd
--- PASS: TestAdd (0.00s)
=== RUN   TestMul
--- PASS: TestMul (0.00s)
PASS
ok      example 0.007s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>如果只想运行其中的一个用例，例如 <code>TestAdd</code>，可以用 <code>-run</code> 参数指定，该参数支持通配符 <code>*</code>，和部分正则表达式，例如 <code>^</code>、<code>$</code>。</p>
<pre class="line-numbers language-shell"><code class="language-shell">$ go test -run TestAdd -v
=== RUN   TestAdd
--- PASS: TestAdd (0.00s)
PASS
ok      example 0.007s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="三、go-test工具"><a href="#三、go-test工具" class="headerlink" title="三、go test工具"></a>三、go test工具</h2><p>Go语言中的测试依赖<code>go test</code>命令。编写测试代码和编写普通的Go代码过程是类似的，并不需要学习新的语法、规则或工具。</p>
<p>go test命令是一个按照一定约定和组织的测试代码的驱动程序。在包目录内，所有以<code>_test.go</code>为后缀名的源代码文件都是<code>go test</code>测试的一部分，不会被<code>go build</code>编译到最终的可执行文件中。</p>
<p>在<code>*_test.go</code>文件中有三种类型的函数，单元测试函数、基准测试函数和示例函数。</p>
<table>
<thead>
<tr>
<th>类型</th>
<th>格式</th>
<th>作用</th>
</tr>
</thead>
<tbody><tr>
<td>测试函数</td>
<td>函数名前缀为Test</td>
<td>测试程序的一些逻辑行为是否正确</td>
</tr>
<tr>
<td>基准函数</td>
<td>函数名前缀为Benchmark</td>
<td>测试函数的性能</td>
</tr>
<tr>
<td>示例函数</td>
<td>函数名前缀为Example</td>
<td>为文档提供示例文档</td>
</tr>
</tbody></table>
<p><code>go test</code>命令会遍历所有的<code>*_test.go</code>文件中符合上述命名规则的函数，然后生成一个临时的main包用于调用相应的测试函数，然后构建并运行、报告测试结果，最后清理测试中生成的临时文件。</p>
<h2 id="四、测试函数"><a href="#四、测试函数" class="headerlink" title="四、测试函数"></a>四、测试函数</h2><p>每个测试函数必须导入<code>testing</code>包，测试函数的基本格式（签名）如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">TestName</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// ...</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>测试函数的名字必须以<code>Test</code>开头，可选的后缀名必须以大写字母开头，举几个例子：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">TestAdd</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span><span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">TestSum</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span><span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">TestLog</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span><span class="token punctuation">{</span> <span class="token operator">...</span> <span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>其中参数<code>t</code>用于报告测试失败和附加的日志信息。 <code>testing.T</code>的拥有的方法如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">Error</span><span class="token punctuation">(</span>args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">Errorf</span><span class="token punctuation">(</span>format <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">Fail</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">FailNow</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">Failed</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">bool</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">Fatal</span><span class="token punctuation">(</span>args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">Fatalf</span><span class="token punctuation">(</span>format <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">Log</span><span class="token punctuation">(</span>args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">Logf</span><span class="token punctuation">(</span>format <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">Name</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>t <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">Parallel</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>t <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">Run</span><span class="token punctuation">(</span>name <span class="token builtin">string</span><span class="token punctuation">,</span> f <span class="token keyword">func</span><span class="token punctuation">(</span>t <span class="token operator">*</span>T<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token builtin">bool</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">Skip</span><span class="token punctuation">(</span>args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">SkipNow</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">Skipf</span><span class="token punctuation">(</span>format <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>T<span class="token punctuation">)</span> <span class="token function">Skipped</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">bool</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>就像细胞是构成我们身体的基本单位，一个软件程序也是由很多单元组件构成的。单元组件可以是函数、结构体、方法和最终用户可能依赖的任意东西。总之我们需要确保这些组件是能够正常运行的。单元测试是一些利用各种方法测试单元组件的程序，它会将结果与预期输出进行比较。</p>
<p>接下来，我们定义一个<code>split</code>的包，包中定义了一个<code>Split</code>函数，具体实现如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token comment" spellcheck="true">// split/split.go</span>

<span class="token keyword">package</span> split

<span class="token keyword">import</span> <span class="token string">"strings"</span>

<span class="token comment" spellcheck="true">// split package with a single split function.</span>

<span class="token comment" spellcheck="true">// Split slices s into all substrings separated by sep and</span>
<span class="token comment" spellcheck="true">// returns a slice of the substrings between those separators.</span>
<span class="token keyword">func</span> <span class="token function">Split</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> sep <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>result <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    i <span class="token operator">:=</span> strings<span class="token punctuation">.</span><span class="token function">Index</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> sep<span class="token punctuation">)</span>

    <span class="token keyword">for</span> i <span class="token operator">></span> <span class="token operator">-</span><span class="token number">1</span> <span class="token punctuation">{</span>
        result <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>result<span class="token punctuation">,</span> s<span class="token punctuation">[</span><span class="token punctuation">:</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span>
        s <span class="token operator">=</span> s<span class="token punctuation">[</span>i<span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">:</span><span class="token punctuation">]</span>
        i <span class="token operator">=</span> strings<span class="token punctuation">.</span><span class="token function">Index</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> sep<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
    result <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>result<span class="token punctuation">,</span> s<span class="token punctuation">)</span>
    <span class="token keyword">return</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>在当前目录下，我们创建一个<code>split_test.go</code>的测试文件，并定义一个测试函数如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token comment" spellcheck="true">// split/split_test.go</span>

<span class="token keyword">package</span> split

<span class="token keyword">import</span> <span class="token punctuation">(</span>
    <span class="token string">"reflect"</span>
    <span class="token string">"testing"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">TestSplit</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// 测试函数名必须以Test开头，必须接收一个*testing.T类型参数</span>
    got <span class="token operator">:=</span> <span class="token function">Split</span><span class="token punctuation">(</span><span class="token string">"a:b:c"</span><span class="token punctuation">,</span> <span class="token string">":"</span><span class="token punctuation">)</span>         <span class="token comment" spellcheck="true">// 程序输出的结果</span>
    want <span class="token operator">:=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"b"</span><span class="token punctuation">,</span> <span class="token string">"c"</span><span class="token punctuation">}</span>    <span class="token comment" spellcheck="true">// 期望的结果</span>
    <span class="token keyword">if</span> <span class="token operator">!</span>reflect<span class="token punctuation">.</span><span class="token function">DeepEqual</span><span class="token punctuation">(</span>want<span class="token punctuation">,</span> got<span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// 因为slice不能比较直接，借助反射包中的方法比较</span>
        t<span class="token punctuation">.</span><span class="token function">Errorf</span><span class="token punctuation">(</span><span class="token string">"excepted:%v, got:%v"</span><span class="token punctuation">,</span> want<span class="token punctuation">,</span> got<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// 测试失败输出错误提示</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>在<code>split</code>包路径下，执行<code>go test</code>命令，可以看到输出结果如下：</p>
<pre><code>split $ go test
PASS
ok      F:/go/test_demo/split       0.005s</code></pre>
<p>一个测试用例有点单薄，我们再编写一个测试使用多个字符切割字符串的例子，在<code>split_test.go</code>中添加如下测试函数：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">TestMoreSplit</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    got <span class="token operator">:=</span> <span class="token function">Split</span><span class="token punctuation">(</span><span class="token string">"abcd"</span><span class="token punctuation">,</span> <span class="token string">"bc"</span><span class="token punctuation">)</span>
    want <span class="token operator">:=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"d"</span><span class="token punctuation">}</span>
    <span class="token keyword">if</span> <span class="token operator">!</span>reflect<span class="token punctuation">.</span><span class="token function">DeepEqual</span><span class="token punctuation">(</span>want<span class="token punctuation">,</span> got<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        t<span class="token punctuation">.</span><span class="token function">Errorf</span><span class="token punctuation">(</span><span class="token string">"excepted:%v, got:%v"</span><span class="token punctuation">,</span> want<span class="token punctuation">,</span> got<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>再次运行<code>go test</code>命令，输出结果如下：</p>
<pre class="line-numbers language-shell"><code class="language-shell">split $ go test
--- FAIL: TestMultiSplit (0.00s)
    split_test.go:20: excepted:[a d], got:[a cd]
FAIL
exit status 1
FAIL    F:/go/test_demo/split       0.006s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这一次，我们的测试失败了。我们可以为<code>go test</code>命令添加<code>-v</code>参数，查看测试函数名称和运行时间：</p>
<pre class="line-numbers language-shell"><code class="language-shell">split $ go test -v
=== RUN   TestSplit
--- PASS: TestSplit (0.00s)
=== RUN   TestMoreSplit
--- FAIL: TestMoreSplit (0.00s)
    split_test.go:21: excepted:[a d], got:[a cd]
FAIL
exit status 1
FAIL    F:/go/test_demo/split       0.005s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这一次我们能清楚的看到是<code>TestMoreSplit</code>这个测试没有成功。 还可以在<code>go test</code>命令后添加<code>-run</code>参数，它对应一个正则表达式，只有函数名匹配上的测试函数才会被<code>go test</code>命令执行。</p>
<pre class="line-numbers language-shell"><code class="language-shell">split $ go test -v -run="More"
=== RUN   TestMoreSplit
--- FAIL: TestMoreSplit (0.00s)
    split_test.go:21: excepted:[a d], got:[a cd]
FAIL
exit status 1
FAIL    F:/go/test_demo/split       0.006s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>现在我们回过头来解决我们程序中的问题。很显然我们最初的<code>split</code>函数并没有考虑到<code>sep</code>为多个字符的情况，我们来修复下这个Bug：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">package</span> split

<span class="token keyword">import</span> <span class="token string">"strings"</span>

<span class="token comment" spellcheck="true">// split package with a single split function.</span>

<span class="token comment" spellcheck="true">// Split slices s into all substrings separated by sep and</span>
<span class="token comment" spellcheck="true">// returns a slice of the substrings between those separators.</span>
<span class="token keyword">func</span> <span class="token function">Split</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> sep <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>result <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    i <span class="token operator">:=</span> strings<span class="token punctuation">.</span><span class="token function">Index</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> sep<span class="token punctuation">)</span>

    <span class="token keyword">for</span> i <span class="token operator">></span> <span class="token operator">-</span><span class="token number">1</span> <span class="token punctuation">{</span>
        result <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>result<span class="token punctuation">,</span> s<span class="token punctuation">[</span><span class="token punctuation">:</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span>
        s <span class="token operator">=</span> s<span class="token punctuation">[</span>i<span class="token operator">+</span><span class="token function">len</span><span class="token punctuation">(</span>sep<span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token punctuation">]</span> <span class="token comment" spellcheck="true">// 这里使用len(sep)获取sep的长度</span>
        i <span class="token operator">=</span> strings<span class="token punctuation">.</span><span class="token function">Index</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> sep<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
    result <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>result<span class="token punctuation">,</span> s<span class="token punctuation">)</span>
    <span class="token keyword">return</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这一次我们再来测试一下，我们的程序。注意，当我们修改了我们的代码之后不要仅仅执行那些失败的测试函数，我们应该完整的运行所有的测试，保证不会因为修改代码而引入了新的问题。</p>
<pre class="line-numbers language-shell"><code class="language-shell">split $ go test -v
=== RUN   TestSplit
--- PASS: TestSplit (0.00s)
=== RUN   TestMoreSplit
--- PASS: TestMoreSplit (0.00s)
PASS
ok      F:/go/test_demo/split      0.006s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这一次我们的测试都通过了。</p>
<h2 id="五、-测试组"><a href="#五、-测试组" class="headerlink" title="五、 测试组"></a>五、 测试组</h2><p>我们现在还想要测试一下<code>split</code>函数对中文字符串的支持，这个时候我们可以再编写一个<code>TestChineseSplit</code>测试函数，但是我们也可以使用如下更友好的一种方式来添加更多的测试用例。</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">TestSplit</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
   <span class="token comment" spellcheck="true">// 定义一个测试用例类型</span>
    <span class="token keyword">type</span> test <span class="token keyword">struct</span> <span class="token punctuation">{</span>
        input <span class="token builtin">string</span>
        sep   <span class="token builtin">string</span>
        want  <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span>
    <span class="token punctuation">}</span>
    <span class="token comment" spellcheck="true">// 定义一个存储测试用例的切片</span>
    tests <span class="token operator">:=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span>test<span class="token punctuation">{</span>
        <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"a:b:c"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">":"</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"b"</span><span class="token punctuation">,</span> <span class="token string">"c"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
        <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"a:b:c"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">","</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"a:b:c"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
        <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"abcd"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">"bc"</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"d"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
        <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"沙河有沙又有河"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">"沙"</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"河有"</span><span class="token punctuation">,</span> <span class="token string">"又有河"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token punctuation">}</span>
    <span class="token comment" spellcheck="true">// 遍历切片，逐一执行测试用例</span>
    <span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> tc <span class="token operator">:=</span> <span class="token keyword">range</span> tests <span class="token punctuation">{</span>
        got <span class="token operator">:=</span> <span class="token function">Split</span><span class="token punctuation">(</span>tc<span class="token punctuation">.</span>input<span class="token punctuation">,</span> tc<span class="token punctuation">.</span>sep<span class="token punctuation">)</span>
        <span class="token keyword">if</span> <span class="token operator">!</span>reflect<span class="token punctuation">.</span><span class="token function">DeepEqual</span><span class="token punctuation">(</span>got<span class="token punctuation">,</span> tc<span class="token punctuation">.</span>want<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            t<span class="token punctuation">.</span><span class="token function">Errorf</span><span class="token punctuation">(</span><span class="token string">"excepted:%v, got:%v"</span><span class="token punctuation">,</span> tc<span class="token punctuation">.</span>want<span class="token punctuation">,</span> got<span class="token punctuation">)</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>我们通过上面的代码把多个测试用例合到一起，再次执行<code>go test</code>命令。</p>
<pre class="line-numbers language-shell"><code class="language-shell">split $ go test -v
=== RUN   TestSplit
--- FAIL: TestSplit (0.00s)
    split_test.go:42: excepted:[河有 又有河], got:[ 河有 又有河]
FAIL
exit status 1
FAIL    F:/go/test_demo/split        0.006s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>我们的测试出现了问题，仔细看打印的测试失败提示信息：<code>excepted:[河有 又有河], got:[ 河有 又有河]</code>，你会发现<code>[ 河有 又有河]</code>中有个不明显的空串，这种情况下十分推荐使用<code>%#v</code>的格式化方式。</p>
<p>我们修改下测试用例的格式化输出错误提示部分：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">TestSplit</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
   <span class="token operator">...</span>

    <span class="token keyword">for</span> <span class="token boolean">_</span><span class="token punctuation">,</span> tc <span class="token operator">:=</span> <span class="token keyword">range</span> tests <span class="token punctuation">{</span>
        got <span class="token operator">:=</span> <span class="token function">Split</span><span class="token punctuation">(</span>tc<span class="token punctuation">.</span>input<span class="token punctuation">,</span> tc<span class="token punctuation">.</span>sep<span class="token punctuation">)</span>
        <span class="token keyword">if</span> <span class="token operator">!</span>reflect<span class="token punctuation">.</span><span class="token function">DeepEqual</span><span class="token punctuation">(</span>got<span class="token punctuation">,</span> tc<span class="token punctuation">.</span>want<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            t<span class="token punctuation">.</span><span class="token function">Errorf</span><span class="token punctuation">(</span><span class="token string">"excepted:%#v, got:%#v"</span><span class="token punctuation">,</span> tc<span class="token punctuation">.</span>want<span class="token punctuation">,</span> got<span class="token punctuation">)</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>此时运行<code>go test</code>命令后就能看到比较明显的提示信息了：</p>
<pre class="line-numbers language-go"><code class="language-go">split $ <span class="token keyword">go</span> test <span class="token operator">-</span>v
<span class="token operator">==</span><span class="token operator">=</span> RUN   TestSplit
<span class="token operator">--</span><span class="token operator">-</span> FAIL<span class="token punctuation">:</span> <span class="token function">TestSplit</span> <span class="token punctuation">(</span><span class="token number">0.</span>00s<span class="token punctuation">)</span>
    split_test<span class="token punctuation">.</span><span class="token keyword">go</span><span class="token punctuation">:</span><span class="token number">42</span><span class="token punctuation">:</span> excepted<span class="token punctuation">:</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"河有"</span><span class="token punctuation">,</span> <span class="token string">"又有河"</span><span class="token punctuation">}</span><span class="token punctuation">,</span> got<span class="token punctuation">:</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">""</span><span class="token punctuation">,</span> <span class="token string">"河有"</span><span class="token punctuation">,</span> <span class="token string">"又有河"</span><span class="token punctuation">}</span>
FAIL
exit status <span class="token number">1</span>
FAIL    F<span class="token punctuation">:</span><span class="token operator">/</span><span class="token keyword">go</span><span class="token operator">/</span>test_demo<span class="token operator">/</span>split         <span class="token number">0.</span>006s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="六、子测试-Subtests"><a href="#六、子测试-Subtests" class="headerlink" title="六、子测试(Subtests)"></a>六、子测试(Subtests)</h2><p>看起来都挺不错的，但是如果测试用例比较多的时候，我们是没办法一眼看出来具体是哪个测试用例失败了。我们可能会想到下面的解决办法：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">TestSplit</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">type</span> test <span class="token keyword">struct</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// 定义test结构体</span>
        input <span class="token builtin">string</span>
        sep   <span class="token builtin">string</span>
        want  <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span>
    <span class="token punctuation">}</span>
    tests <span class="token operator">:=</span> <span class="token keyword">map</span><span class="token punctuation">[</span><span class="token builtin">string</span><span class="token punctuation">]</span>test<span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// 测试用例使用map存储</span>
        <span class="token string">"simple"</span><span class="token punctuation">:</span>      <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"a:b:c"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">":"</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"b"</span><span class="token punctuation">,</span> <span class="token string">"c"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
        <span class="token string">"wrong sep"</span><span class="token punctuation">:</span>   <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"a:b:c"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">","</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"a:b:c"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
        <span class="token string">"more sep"</span><span class="token punctuation">:</span>    <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"abcd"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">"bc"</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"d"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
        <span class="token string">"leading sep"</span><span class="token punctuation">:</span> <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"沙河有沙又有河"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">"沙"</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"河有"</span><span class="token punctuation">,</span> <span class="token string">"又有河"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">for</span> name<span class="token punctuation">,</span> tc <span class="token operator">:=</span> <span class="token keyword">range</span> tests <span class="token punctuation">{</span>
        got <span class="token operator">:=</span> <span class="token function">Split</span><span class="token punctuation">(</span>tc<span class="token punctuation">.</span>input<span class="token punctuation">,</span> tc<span class="token punctuation">.</span>sep<span class="token punctuation">)</span>
        <span class="token keyword">if</span> <span class="token operator">!</span>reflect<span class="token punctuation">.</span><span class="token function">DeepEqual</span><span class="token punctuation">(</span>got<span class="token punctuation">,</span> tc<span class="token punctuation">.</span>want<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            t<span class="token punctuation">.</span><span class="token function">Errorf</span><span class="token punctuation">(</span><span class="token string">"name:%s excepted:%#v, got:%#v"</span><span class="token punctuation">,</span> name<span class="token punctuation">,</span> tc<span class="token punctuation">.</span>want<span class="token punctuation">,</span> got<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// 将测试用例的name格式化输出</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>上面的做法是能够解决问题的。同时Go1.7+中新增了子测试，我们可以按照如下方式使用<code>t.Run</code>执行子测试：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">TestSplit</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">type</span> test <span class="token keyword">struct</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// 定义test结构体</span>
        input <span class="token builtin">string</span>
        sep   <span class="token builtin">string</span>
        want  <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span>
    <span class="token punctuation">}</span>
    tests <span class="token operator">:=</span> <span class="token keyword">map</span><span class="token punctuation">[</span><span class="token builtin">string</span><span class="token punctuation">]</span>test<span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// 测试用例使用map存储</span>
        <span class="token string">"simple"</span><span class="token punctuation">:</span>      <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"a:b:c"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">":"</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"b"</span><span class="token punctuation">,</span> <span class="token string">"c"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
        <span class="token string">"wrong sep"</span><span class="token punctuation">:</span>   <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"a:b:c"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">","</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"a:b:c"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
        <span class="token string">"more sep"</span><span class="token punctuation">:</span>    <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"abcd"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">"bc"</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"d"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
        <span class="token string">"leading sep"</span><span class="token punctuation">:</span> <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"沙河有沙又有河"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">"沙"</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"河有"</span><span class="token punctuation">,</span> <span class="token string">"又有河"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">for</span> name<span class="token punctuation">,</span> tc <span class="token operator">:=</span> <span class="token keyword">range</span> tests <span class="token punctuation">{</span>
        t<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span>name<span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// 使用t.Run()执行子测试</span>
            got <span class="token operator">:=</span> <span class="token function">Split</span><span class="token punctuation">(</span>tc<span class="token punctuation">.</span>input<span class="token punctuation">,</span> tc<span class="token punctuation">.</span>sep<span class="token punctuation">)</span>
            <span class="token keyword">if</span> <span class="token operator">!</span>reflect<span class="token punctuation">.</span><span class="token function">DeepEqual</span><span class="token punctuation">(</span>got<span class="token punctuation">,</span> tc<span class="token punctuation">.</span>want<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                t<span class="token punctuation">.</span><span class="token function">Errorf</span><span class="token punctuation">(</span><span class="token string">"excepted:%#v, got:%#v"</span><span class="token punctuation">,</span> tc<span class="token punctuation">.</span>want<span class="token punctuation">,</span> got<span class="token punctuation">)</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>此时我们再执行<code>go test</code>命令就能够看到更清晰的输出内容了：</p>
<pre class="line-numbers language-shell"><code class="language-shell">split $ go test -v
=== RUN   TestSplit
=== RUN   TestSplit/leading_sep
=== RUN   TestSplit/simple
=== RUN   TestSplit/wrong_sep
=== RUN   TestSplit/more_sep
--- FAIL: TestSplit (0.00s)
    --- FAIL: TestSplit/leading_sep (0.00s)
        split_test.go:83: excepted:[]string{"河有", "又有河"}, got:[]string{"", "河有", "又有河"}
    --- PASS: TestSplit/simple (0.00s)
    --- PASS: TestSplit/wrong_sep (0.00s)
    --- PASS: TestSplit/more_sep (0.00s)
FAIL
exit status 1
FAIL   F:/go/test_demo/split         0.006s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这个时候我们要把测试用例中的错误修改回来：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">TestSplit</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token operator">...</span>
    tests <span class="token operator">:=</span> <span class="token keyword">map</span><span class="token punctuation">[</span><span class="token builtin">string</span><span class="token punctuation">]</span>test<span class="token punctuation">{</span> <span class="token comment" spellcheck="true">// 测试用例使用map存储</span>
        <span class="token string">"simple"</span><span class="token punctuation">:</span>      <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"a:b:c"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">":"</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"b"</span><span class="token punctuation">,</span> <span class="token string">"c"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
        <span class="token string">"wrong sep"</span><span class="token punctuation">:</span>   <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"a:b:c"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">","</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"a:b:c"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
        <span class="token string">"more sep"</span><span class="token punctuation">:</span>    <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"abcd"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">"bc"</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">"a"</span><span class="token punctuation">,</span> <span class="token string">"d"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
        <span class="token string">"leading sep"</span><span class="token punctuation">:</span> <span class="token punctuation">{</span>input<span class="token punctuation">:</span> <span class="token string">"沙河有沙又有河"</span><span class="token punctuation">,</span> sep<span class="token punctuation">:</span> <span class="token string">"沙"</span><span class="token punctuation">,</span> want<span class="token punctuation">:</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">{</span><span class="token string">""</span><span class="token punctuation">,</span> <span class="token string">"河有"</span><span class="token punctuation">,</span> <span class="token string">"又有河"</span><span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token punctuation">,</span>
    <span class="token punctuation">}</span>
    <span class="token operator">...</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>我们都知道可以通过<code>-run=RegExp</code>来指定运行的测试用例，还可以通过<code>/</code>来指定要运行的子测试用例，例如：<code>go test -v -run=Split/simple</code>只会运行<code>simple</code>对应的子测试用例。</p>
<p>我们再看一个示例：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token comment" spellcheck="true">// calc_test.go</span>

<span class="token keyword">func</span> <span class="token function">TestMul</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    t<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span><span class="token string">"pos"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token function">Mul</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token number">6</span> <span class="token punctuation">{</span>
            t<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span><span class="token string">"fail"</span><span class="token punctuation">)</span>
        <span class="token punctuation">}</span>

    <span class="token punctuation">}</span><span class="token punctuation">)</span>
    t<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span><span class="token string">"neg"</span><span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token function">Mul</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">3</span><span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token operator">-</span><span class="token number">6</span> <span class="token punctuation">{</span>
            t<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span><span class="token string">"fail"</span><span class="token punctuation">)</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>之前的例子测试失败时使用 <code>t.Error/t.Errorf</code>，这个例子中使用 <code>t.Fatal/t.Fatalf</code>，区别在于前者遇错不停，还会继续执行其他的测试用例，后者遇错即停。</li>
</ul>
<p>运行某个测试用例的子测试：</p>
<pre class="line-numbers language-shell"><code class="language-shell">$ go test -run TestMul/pos -v
=== RUN   TestMul
=== RUN   TestMul/pos
--- PASS: TestMul (0.00s)
    --- PASS: TestMul/pos (0.00s)
PASS
ok      example 0.008s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>对于多个子测试的场景，更推荐如下的写法(table-driven tests)：</p>
<pre class="line-numbers language-shell"><code class="language-shell">//  calc_test.go
func TestMul(t *testing.T) {
    cases := []struct {
        Name           string
        A, B, Expected int
    }{
        {"pos", 2, 3, 6},
        {"neg", 2, -3, -6},
        {"zero", 2, 0, 0},
    }

    for _, c := range cases {
        t.Run(c.Name, func(t *testing.T) {
            if ans := Mul(c.A, c.B); ans != c.Expected {
                t.Fatalf("%d * %d expected %d, but %d got",
                    c.A, c.B, c.Expected, ans)
            }
        })
    }
}<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>所有用例的数据组织在切片 <code>cases</code> 中，看起来就像一张表，借助循环创建子测试。这样写的好处有：</p>
<ul>
<li>新增用例非常简单，只需给 cases 新增一条测试数据即可。</li>
<li>测试代码可读性好，直观地能够看到每个子测试的参数和期待的返回值。</li>
<li>用例失败时，报错信息的格式比较统一，测试报告易于阅读。</li>
</ul>
<p>如果数据量较大，或是一些二进制数据，推荐使用相对路径从文件中读取。</p>
<h2 id="七、测试覆盖率"><a href="#七、测试覆盖率" class="headerlink" title="七、测试覆盖率"></a>七、测试覆盖率</h2><p>测试覆盖率是你的代码被测试套件覆盖的百分比。通常我们使用的都是语句的覆盖率，也就是在测试中至少被运行一次的代码占总代码的比例。</p>
<p>Go提供内置功能来检查你的代码覆盖率。我们可以使用<code>go test -cover</code>来查看测试覆盖率。例如：</p>
<pre class="line-numbers language-go"><code class="language-go">split $ <span class="token keyword">go</span> test <span class="token operator">-</span>cover
PASS
coverage<span class="token punctuation">:</span> <span class="token number">100.0</span><span class="token operator">%</span> of statements
ok      split       <span class="token number">0.</span>005s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>从上面的结果可以看到我们的测试用例覆盖了100%的代码。</p>
<p>Go还提供了一个额外的<code>-coverprofile</code>参数，用来将覆盖率相关的记录信息输出到一个文件。例如：</p>
<pre class="line-numbers language-shell"><code class="language-shell">split $ go test -cover -coverprofile=c.out
PASS
coverage: 100.0% of statements
ok      split       0.005s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>上面的命令会将覆盖率相关的信息输出到当前文件夹下面的<code>c.out</code>文件中，然后我们执行<code>go tool cover -html=c.out</code>，使用<code>cover</code>工具来处理生成的记录信息，该命令会打开本地的浏览器窗口生成一个HTML报告。<img src="https://img2020.cnblogs.com/blog/1476293/202005/1476293-20200517210718139-1245599752.png" alt="img"></p>
<p> 图中每个用绿色标记的语句块表示被覆盖了，而红色的表示没有被覆盖。</p>
<h2 id="八、帮助函数-helpers"><a href="#八、帮助函数-helpers" class="headerlink" title="八、帮助函数(helpers)"></a>八、帮助函数(helpers)</h2><p>对一些重复的逻辑，抽取出来作为公共的帮助函数(helpers)，可以增加测试代码的可读性和可维护性。 借助帮助函数，可以让测试用例的主逻辑看起来更清晰。</p>
<p>例如，我们可以将创建子测试的逻辑抽取出来：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token comment" spellcheck="true">// calc_test.go</span>
<span class="token keyword">package</span> main

<span class="token keyword">import</span> <span class="token string">"testing"</span>

<span class="token keyword">type</span> calcCase <span class="token keyword">struct</span><span class="token punctuation">{</span> A<span class="token punctuation">,</span> B<span class="token punctuation">,</span> Expected <span class="token builtin">int</span> <span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">createMulTestCase</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">,</span> c <span class="token operator">*</span>calcCase<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// t.Helper()</span>
    <span class="token keyword">if</span> ans <span class="token operator">:=</span> <span class="token function">Mul</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span>A<span class="token punctuation">,</span> c<span class="token punctuation">.</span>B<span class="token punctuation">)</span><span class="token punctuation">;</span> ans <span class="token operator">!=</span> c<span class="token punctuation">.</span>Expected <span class="token punctuation">{</span>
        t<span class="token punctuation">.</span><span class="token function">Fatalf</span><span class="token punctuation">(</span><span class="token string">"%d * %d expected %d, but %d got"</span><span class="token punctuation">,</span>
            c<span class="token punctuation">.</span>A<span class="token punctuation">,</span> c<span class="token punctuation">.</span>B<span class="token punctuation">,</span> c<span class="token punctuation">.</span>Expected<span class="token punctuation">,</span> ans<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">TestMul</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">createMulTestCase</span><span class="token punctuation">(</span>t<span class="token punctuation">,</span> <span class="token operator">&amp;</span>calcCase<span class="token punctuation">{</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token function">createMulTestCase</span><span class="token punctuation">(</span>t<span class="token punctuation">,</span> <span class="token operator">&amp;</span>calcCase<span class="token punctuation">{</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">3</span><span class="token punctuation">,</span> <span class="token operator">-</span><span class="token number">6</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
    <span class="token function">createMulTestCase</span><span class="token punctuation">(</span>t<span class="token punctuation">,</span> <span class="token operator">&amp;</span>calcCase<span class="token punctuation">{</span><span class="token number">2</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">}</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// wrong case</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>在这里，我们故意创建了一个错误的测试用例，运行 <code>go test</code>，用例失败，会报告错误发生的文件和行号信息：</p>
<pre class="line-numbers language-shell"><code class="language-shell">$ go test
--- FAIL: TestMul (0.00s)
    calc_test.go:11: 2 * 0 expected 1, but 0 got
FAIL
exit status 1
FAIL    example 0.007s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>可以看到，错误发生在第11行，也就是帮助函数 <code>createMulTestCase</code> 内部。18, 19, 20行都调用了该方法，我们第一时间并不能够确定是哪一行发生了错误。有些帮助函数还可能在不同的函数中被调用，报错信息都在同一处，不方便问题定位。因此，Go 语言在 1.9 版本中引入了 <code>t.Helper()</code>，用于标注该函数是帮助函数，报错时将输出帮助函数调用者的信息，而不是帮助函数的内部信息。</p>
<p>修改 <code>createMulTestCase</code>，调用 <code>t.Helper()</code></p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">createMulTestCase</span><span class="token punctuation">(</span>c <span class="token operator">*</span>calcCase<span class="token punctuation">,</span> t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    t<span class="token punctuation">.</span><span class="token function">Helper</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    t<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span>Name<span class="token punctuation">,</span> <span class="token keyword">func</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span> ans <span class="token operator">:=</span> <span class="token function">Mul</span><span class="token punctuation">(</span>c<span class="token punctuation">.</span>A<span class="token punctuation">,</span> c<span class="token punctuation">.</span>B<span class="token punctuation">)</span><span class="token punctuation">;</span> ans <span class="token operator">!=</span> c<span class="token punctuation">.</span>Expected <span class="token punctuation">{</span>
            t<span class="token punctuation">.</span><span class="token function">Fatalf</span><span class="token punctuation">(</span><span class="token string">"%d * %d expected %d, but %d got"</span><span class="token punctuation">,</span>
                c<span class="token punctuation">.</span>A<span class="token punctuation">,</span> c<span class="token punctuation">.</span>B<span class="token punctuation">,</span> c<span class="token punctuation">.</span>Expected<span class="token punctuation">,</span> ans<span class="token punctuation">)</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>运行 <code>go test</code>，报错信息如下，可以非常清晰地知道，错误发生在第 20 行。</p>
<pre class="line-numbers language-shell"><code class="language-shell">$ go test
--- FAIL: TestMul (0.00s)
    calc_test.go:20: 2 * 0 expected 1, but 0 got
FAIL
exit status 1
FAIL    example 0.006s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>关于 <code>helper</code> 函数的 2 个建议：</p>
<ul>
<li>不要返回错误， 帮助函数内部直接使用 <code>t.Error</code> 或 <code>t.Fatal</code> 即可，在用例主逻辑中不会因为太多的错误处理代码，影响可读性。</li>
<li>调用 <code>t.Helper()</code> 让报错信息更准确，有助于定位。</li>
</ul>
<h2 id="九、setup-和-teardown"><a href="#九、setup-和-teardown" class="headerlink" title="九、setup 和 teardown"></a>九、setup 和 teardown</h2><p>如果在同一个测试文件中，每一个测试用例运行前后的逻辑是相同的，一般会写在 setup 和 teardown 函数中。例如执行前需要实例化待测试的对象，如果这个对象比较复杂，很适合将这一部分逻辑提取出来；执行后，可能会做一些资源回收类的工作，例如关闭网络连接，释放文件等。标准库 <code>testing</code> 提供了这样的机制：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">setup</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"Before all tests"</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">teardown</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"After all tests"</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">Test1</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"I'm test1"</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">Test2</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span><span class="token string">"I'm test2"</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">TestMain</span><span class="token punctuation">(</span>m <span class="token operator">*</span>testing<span class="token punctuation">.</span>M<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">setup</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    code <span class="token operator">:=</span> m<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token function">teardown</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    os<span class="token punctuation">.</span><span class="token function">Exit</span><span class="token punctuation">(</span>code<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li>在这个测试文件中，包含有2个测试用例，<code>Test1</code> 和 <code>Test2</code>。</li>
<li>如果测试文件中包含函数 <code>TestMain</code>，那么生成的测试将调用 TestMain(m)，而不是直接运行测试。</li>
<li>调用 <code>m.Run()</code> 触发所有测试用例的执行，并使用 <code>os.Exit()</code> 处理返回的状态码，如果不为0，说明有用例失败。</li>
<li>因此可以在调用 <code>m.Run()</code> 前后做一些额外的准备(setup)和回收(teardown)工作。</li>
</ul>
<p>执行 <code>go test</code>，将会输出</p>
<pre class="line-numbers language-shell"><code class="language-shell">$ go test
Before all tests
I'm test1
I'm test2
PASS
After all tests
ok      example 0.006s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h2 id="十、基准测试"><a href="#十、基准测试" class="headerlink" title="十、基准测试"></a>十、基准测试</h2><h3 id="1-基准测试格式"><a href="#1-基准测试格式" class="headerlink" title="1. 基准测试格式"></a>1. 基准测试格式</h3><p>基准测试就是在一定的工作负载之下检测程序性能的一种方法。基准测试的基本格式如下：</p>
<p>基准测试用例的定义如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">BenchmarkName</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// ...</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<ul>
<li>函数名必须以 <code>Benchmark</code> 开头，后面一般跟待测试的函数名</li>
<li>参数为 <code>b *testing.B</code>。</li>
<li>执行基准测试时，需要添加 <code>-bench</code> 参数。</li>
<li>基准测试必须要执行<code>b.N</code>次，这样的测试才有对照性，<code>b.N</code>的值是系统根据实际情况去调整的，从而保证测试的稳定性。</li>
</ul>
<p><code>testing.B</code>拥有的方法如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">Error</span><span class="token punctuation">(</span>args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">Errorf</span><span class="token punctuation">(</span>format <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">Fail</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">FailNow</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">Failed</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">bool</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">Fatal</span><span class="token punctuation">(</span>args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">Fatalf</span><span class="token punctuation">(</span>format <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">Log</span><span class="token punctuation">(</span>args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">Logf</span><span class="token punctuation">(</span>format <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">Name</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">string</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>b <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">ReportAllocs</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>b <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">ResetTimer</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>b <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">Run</span><span class="token punctuation">(</span>name <span class="token builtin">string</span><span class="token punctuation">,</span> f <span class="token keyword">func</span><span class="token punctuation">(</span>b <span class="token operator">*</span>B<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token builtin">bool</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>b <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">RunParallel</span><span class="token punctuation">(</span>body <span class="token keyword">func</span><span class="token punctuation">(</span><span class="token operator">*</span>PB<span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>b <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">SetBytes</span><span class="token punctuation">(</span>n <span class="token builtin">int64</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>b <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">SetParallelism</span><span class="token punctuation">(</span>p <span class="token builtin">int</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">Skip</span><span class="token punctuation">(</span>args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">SkipNow</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">Skipf</span><span class="token punctuation">(</span>format <span class="token builtin">string</span><span class="token punctuation">,</span> args <span class="token operator">...</span><span class="token keyword">interface</span><span class="token punctuation">{</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>c <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">Skipped</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token builtin">bool</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>b <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">StartTimer</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">func</span> <span class="token punctuation">(</span>b <span class="token operator">*</span>B<span class="token punctuation">)</span> <span class="token function">StopTimer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>例如：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">BenchmarkHello</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> b<span class="token punctuation">.</span>N<span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
        fmt<span class="token punctuation">.</span><span class="token function">Sprintf</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
$ <span class="token keyword">go</span> test <span class="token operator">-</span>benchmem <span class="token operator">-</span>bench <span class="token punctuation">.</span>
<span class="token operator">...</span>
BenchmarkHello<span class="token number">-16</span>   <span class="token number">15991854</span>   <span class="token number">71.6</span> ns<span class="token operator">/</span>op   <span class="token number">5</span> B<span class="token operator">/</span>op   <span class="token number">1</span> allocs<span class="token operator">/</span>op
<span class="token operator">...</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>基准测试报告每一列值对应的含义如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">type</span> BenchmarkResult <span class="token keyword">struct</span> <span class="token punctuation">{</span>
    N         <span class="token builtin">int</span>           <span class="token comment" spellcheck="true">// 迭代次数</span>
    T         time<span class="token punctuation">.</span>Duration <span class="token comment" spellcheck="true">// 基准测试花费的时间</span>
    Bytes     <span class="token builtin">int64</span>         <span class="token comment" spellcheck="true">// 一次迭代处理的字节数</span>
    MemAllocs <span class="token builtin">uint64</span>        <span class="token comment" spellcheck="true">// 总的分配内存的次数</span>
    MemBytes  <span class="token builtin">uint64</span>        <span class="token comment" spellcheck="true">// 总的分配内存的字节数</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>如果在运行前基准测试需要一些耗时的配置，则可以使用 <code>b.ResetTimer()</code> 先重置定时器，例如：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">BenchmarkHello</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token operator">...</span> <span class="token comment" spellcheck="true">// 耗时操作</span>
    b<span class="token punctuation">.</span><span class="token function">ResetTimer</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> b<span class="token punctuation">.</span>N<span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
        fmt<span class="token punctuation">.</span><span class="token function">Sprintf</span><span class="token punctuation">(</span><span class="token string">"hello"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>使用 <code>RunParallel</code> 测试并发性能</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">BenchmarkParallel</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    templ <span class="token operator">:=</span> template<span class="token punctuation">.</span><span class="token function">Must</span><span class="token punctuation">(</span>template<span class="token punctuation">.</span><span class="token function">New</span><span class="token punctuation">(</span><span class="token string">"test"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Parse</span><span class="token punctuation">(</span><span class="token string">"Hello, {{.}}!"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    b<span class="token punctuation">.</span><span class="token function">RunParallel</span><span class="token punctuation">(</span><span class="token keyword">func</span><span class="token punctuation">(</span>pb <span class="token operator">*</span>testing<span class="token punctuation">.</span>PB<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">var</span> buf bytes<span class="token punctuation">.</span>Buffer
        <span class="token keyword">for</span> pb<span class="token punctuation">.</span><span class="token function">Next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token comment" spellcheck="true">// 所有 goroutine 一起，循环一共执行 b.N 次</span>
            buf<span class="token punctuation">.</span><span class="token function">Reset</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
            templ<span class="token punctuation">.</span><span class="token function">Execute</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>buf<span class="token punctuation">,</span> <span class="token string">"World"</span><span class="token punctuation">)</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span>
$ <span class="token keyword">go</span> test <span class="token operator">-</span>benchmem <span class="token operator">-</span>bench <span class="token punctuation">.</span>
<span class="token operator">...</span>
BenchmarkParallel<span class="token number">-16</span>   <span class="token number">3325430</span>     <span class="token number">375</span> ns<span class="token operator">/</span>op   <span class="token number">272</span> B<span class="token operator">/</span>op   <span class="token number">8</span> allocs<span class="token operator">/</span>op
<span class="token operator">...</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="2-基准测试示例"><a href="#2-基准测试示例" class="headerlink" title="2. 基准测试示例"></a>2. 基准测试示例</h3><p>我们为split包中的<code>Split</code>函数编写基准测试如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">BenchmarkSplit</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> b<span class="token punctuation">.</span>N<span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
        <span class="token function">Split</span><span class="token punctuation">(</span><span class="token string">"沙河有沙又有河"</span><span class="token punctuation">,</span> <span class="token string">"沙"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>基准测试并不会默认执行，需要增加<code>-bench</code>参数，所以我们通过执行<code>go test -bench=Split</code>命令执行基准测试，输出结果如下：</p>
<pre class="line-numbers language-go"><code class="language-go">split $ <span class="token keyword">go</span> test <span class="token operator">-</span>bench<span class="token operator">=</span>Split
goos<span class="token punctuation">:</span> darwin
goarch<span class="token punctuation">:</span> amd64
pkg<span class="token punctuation">:</span> split
BenchmarkSplit<span class="token number">-8</span>        <span class="token number">10000000</span>               <span class="token number">203</span> ns<span class="token operator">/</span>op
PASS
ok      split       <span class="token number">2.</span>255s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>其中<code>BenchmarkSplit-8</code>表示对Split函数进行基准测试，数字<code>8</code>表示<code>GOMAXPROCS</code>的值，这个对于并发基准测试很重要。<code>10000000</code>和<code>203ns/op</code>表示每次调用<code>Split</code>函数耗时<code>203ns</code>，这个结果是<code>10000000</code>次调用的平均值。</p>
<p>我们还可以为基准测试添加<code>-benchmem</code>参数，来获得内存分配的统计数据。</p>
<pre class="line-numbers language-shell"><code class="language-shell">split $ go test -bench=Split -benchmem
goos: darwin
goarch: amd64
pkg: split
BenchmarkSplit-8        10000000               215 ns/op             112 B/op          3 allocs/op
PASS
ok      split       2.394s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>其中，<code>112 B/op</code>表示每次操作内存分配了112字节，<code>3 allocs/op</code>则表示每次操作进行了3次内存分配。 我们将我们的<code>Split</code>函数优化如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">Split</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> sep <span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">(</span>result <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    result <span class="token operator">=</span> <span class="token function">make</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token builtin">string</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">,</span> strings<span class="token punctuation">.</span><span class="token function">Count</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> sep<span class="token punctuation">)</span><span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">)</span>
    i <span class="token operator">:=</span> strings<span class="token punctuation">.</span><span class="token function">Index</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> sep<span class="token punctuation">)</span>
    <span class="token keyword">for</span> i <span class="token operator">></span> <span class="token operator">-</span><span class="token number">1</span> <span class="token punctuation">{</span>
        result <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>result<span class="token punctuation">,</span> s<span class="token punctuation">[</span><span class="token punctuation">:</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span>
        s <span class="token operator">=</span> s<span class="token punctuation">[</span>i<span class="token operator">+</span><span class="token function">len</span><span class="token punctuation">(</span>sep<span class="token punctuation">)</span><span class="token punctuation">:</span><span class="token punctuation">]</span> <span class="token comment" spellcheck="true">// 这里使用len(sep)获取sep的长度</span>
        i <span class="token operator">=</span> strings<span class="token punctuation">.</span><span class="token function">Index</span><span class="token punctuation">(</span>s<span class="token punctuation">,</span> sep<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
    result <span class="token operator">=</span> <span class="token function">append</span><span class="token punctuation">(</span>result<span class="token punctuation">,</span> s<span class="token punctuation">)</span>
    <span class="token keyword">return</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这一次我们提前使用make函数将result初始化为一个容量足够大的切片，而不再像之前一样通过调用append函数来追加。我们来看一下这个改进会带来多大的性能提升：</p>
<pre class="line-numbers language-go"><code class="language-go">split $ <span class="token keyword">go</span> test <span class="token operator">-</span>bench<span class="token operator">=</span>Split <span class="token operator">-</span>benchmem
goos<span class="token punctuation">:</span> darwin
goarch<span class="token punctuation">:</span> amd64
pkg<span class="token punctuation">:</span> split
BenchmarkSplit<span class="token number">-8</span>        <span class="token number">10000000</span>               <span class="token number">127</span> ns<span class="token operator">/</span>op              <span class="token number">48</span> B<span class="token operator">/</span>op          <span class="token number">1</span> allocs<span class="token operator">/</span>op
PASS
ok      split       <span class="token number">1.</span>423s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这个使用make函数提前分配内存的改动，减少了2/3的内存分配次数，并且减少了一半的内存分配。</p>
<h3 id="3-性能比较函数"><a href="#3-性能比较函数" class="headerlink" title="3. 性能比较函数"></a>3. 性能比较函数</h3><p>上面的基准测试只能得到给定操作的绝对耗时，但是在很多性能问题是发生在两个不同操作之间的相对耗时，比如同一个函数处理1000个元素的耗时与处理1万甚至100万个元素的耗时的差别是多少？再或者对于同一个任务究竟使用哪种算法性能最佳？我们通常需要对两个不同算法的实现使用相同的输入来进行基准比较测试。</p>
<p>性能比较函数通常是一个带有参数的函数，被多个不同的Benchmark函数传入不同的值来调用。举个例子如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">benchmark</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">,</span> size <span class="token builtin">int</span><span class="token punctuation">)</span><span class="token punctuation">{</span><span class="token comment" spellcheck="true">/* ... */</span><span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">Benchmark10</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span><span class="token punctuation">{</span> <span class="token function">benchmark</span><span class="token punctuation">(</span>b<span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span> <span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">Benchmark100</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span><span class="token punctuation">{</span> <span class="token function">benchmark</span><span class="token punctuation">(</span>b<span class="token punctuation">,</span> <span class="token number">100</span><span class="token punctuation">)</span> <span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">Benchmark1000</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span><span class="token punctuation">{</span> <span class="token function">benchmark</span><span class="token punctuation">(</span>b<span class="token punctuation">,</span> <span class="token number">1000</span><span class="token punctuation">)</span> <span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>
<p>例如我们编写了一个计算斐波那契数列的函数如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token comment" spellcheck="true">// fib.go</span>

<span class="token comment" spellcheck="true">// Fib 是一个计算第n个斐波那契数的函数</span>
<span class="token keyword">func</span> <span class="token function">Fib</span><span class="token punctuation">(</span>n <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token builtin">int</span> <span class="token punctuation">{</span>
    <span class="token keyword">if</span> n <span class="token operator">&lt;</span> <span class="token number">2</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> n
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> <span class="token function">Fib</span><span class="token punctuation">(</span>n<span class="token number">-1</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token function">Fib</span><span class="token punctuation">(</span>n<span class="token number">-2</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>我们编写的性能比较函数如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token comment" spellcheck="true">// fib_test.go</span>

<span class="token keyword">func</span> <span class="token function">benchmarkFib</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">,</span> n <span class="token builtin">int</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> b<span class="token punctuation">.</span>N<span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
        <span class="token function">Fib</span><span class="token punctuation">(</span>n<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">BenchmarkFib1</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span>  <span class="token punctuation">{</span> <span class="token function">benchmarkFib</span><span class="token punctuation">(</span>b<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">BenchmarkFib2</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span>  <span class="token punctuation">{</span> <span class="token function">benchmarkFib</span><span class="token punctuation">(</span>b<span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">)</span> <span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">BenchmarkFib3</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span>  <span class="token punctuation">{</span> <span class="token function">benchmarkFib</span><span class="token punctuation">(</span>b<span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span> <span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">BenchmarkFib10</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token function">benchmarkFib</span><span class="token punctuation">(</span>b<span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">)</span> <span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">BenchmarkFib20</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token function">benchmarkFib</span><span class="token punctuation">(</span>b<span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">)</span> <span class="token punctuation">}</span>
<span class="token keyword">func</span> <span class="token function">BenchmarkFib40</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token function">benchmarkFib</span><span class="token punctuation">(</span>b<span class="token punctuation">,</span> <span class="token number">40</span><span class="token punctuation">)</span> <span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>运行基准测试：</p>
<pre class="line-numbers language-shell"><code class="language-shell">split $ go test -bench=.
goos: darwin
goarch: amd64
pkg: fib
BenchmarkFib1-8         1000000000               2.03 ns/op
BenchmarkFib2-8         300000000                5.39 ns/op
BenchmarkFib3-8         200000000                9.71 ns/op
BenchmarkFib10-8         5000000               325 ns/op
BenchmarkFib20-8           30000             42460 ns/op
BenchmarkFib40-8               2         638524980 ns/op
PASS
ok      fib 12.944s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这里需要注意的是，默认情况下，每个基准测试至少运行1秒。如果在Benchmark函数返回时没有到1秒，则b.N的值会按1,2,5,10,20,50，…增加，并且函数再次运行。</p>
<p>最终的BenchmarkFib40只运行了两次，每次运行的平均值只有不到一秒。像这种情况下我们应该可以使用<code>-benchtime</code>标志增加最小基准时间，以产生更准确的结果。例如：</p>
<pre class="line-numbers language-shell"><code class="language-shell">split $ go test -bench=Fib40 -benchtime=20s
goos: darwin
goarch: amd64
pkg: fib
BenchmarkFib40-8              50         663205114 ns/op
PASS
ok      fib 33.849s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>这一次<code>BenchmarkFib40</code>函数运行了50次，结果就会更准确一些了。</p>
<p>使用性能比较函数做测试的时候一个容易犯的错误就是把<code>b.N</code>作为输入的大小，例如以下两个例子都是错误的示范：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token comment" spellcheck="true">// 错误示范1</span>
<span class="token keyword">func</span> <span class="token function">BenchmarkFibWrong</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">for</span> n <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> n <span class="token operator">&lt;</span> b<span class="token punctuation">.</span>N<span class="token punctuation">;</span> n<span class="token operator">++</span> <span class="token punctuation">{</span>
        <span class="token function">Fib</span><span class="token punctuation">(</span>n<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">// 错误示范2</span>
<span class="token keyword">func</span> <span class="token function">BenchmarkFibWrong2</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token function">Fib</span><span class="token punctuation">(</span>b<span class="token punctuation">.</span>N<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="4-重置时间"><a href="#4-重置时间" class="headerlink" title="4. 重置时间"></a>4. 重置时间</h3><p><code>b.ResetTimer</code>之前的处理不会放到执行时间里，也不会输出到报告中，所以可以在之前做一些不计划作为测试报告的操作。例如：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">BenchmarkSplit</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    time<span class="token punctuation">.</span><span class="token function">Sleep</span><span class="token punctuation">(</span><span class="token number">5</span> <span class="token operator">*</span> time<span class="token punctuation">.</span>Second<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// 假设需要做一些耗时的无关操作</span>
    b<span class="token punctuation">.</span><span class="token function">ResetTimer</span><span class="token punctuation">(</span><span class="token punctuation">)</span>              <span class="token comment" spellcheck="true">// 重置计时器</span>
    <span class="token keyword">for</span> i <span class="token operator">:=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> b<span class="token punctuation">.</span>N<span class="token punctuation">;</span> i<span class="token operator">++</span> <span class="token punctuation">{</span>
        <span class="token function">Split</span><span class="token punctuation">(</span><span class="token string">"沙河有沙又有河"</span><span class="token punctuation">,</span> <span class="token string">"沙"</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<h3 id="5-并行测试"><a href="#5-并行测试" class="headerlink" title="5. 并行测试"></a>5. 并行测试</h3><p><code>func (b *B) RunParallel(body func(*PB))</code>会以并行的方式执行给定的基准测试。</p>
<p><code>RunParallel</code>会创建出多个<code>goroutine</code>，并将<code>b.N</code>分配给这些<code>goroutine</code>执行， 其中<code>goroutine</code>数量的默认值为<code>GOMAXPROCS</code>。用户如果想要增加非CPU受限（non-CPU-bound）基准测试的并行性， 那么可以在<code>RunParallel</code>之前调用<code>SetParallelism</code> 。<code>RunParallel</code>通常会与<code>-cpu</code>标志一同使用。</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">BenchmarkSplitParallel</span><span class="token punctuation">(</span>b <span class="token operator">*</span>testing<span class="token punctuation">.</span>B<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// b.SetParallelism(1) // 设置使用的CPU数</span>
    b<span class="token punctuation">.</span><span class="token function">RunParallel</span><span class="token punctuation">(</span><span class="token keyword">func</span><span class="token punctuation">(</span>pb <span class="token operator">*</span>testing<span class="token punctuation">.</span>PB<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">for</span> pb<span class="token punctuation">.</span><span class="token function">Next</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token function">Split</span><span class="token punctuation">(</span><span class="token string">"沙河有沙又有河"</span><span class="token punctuation">,</span> <span class="token string">"沙"</span><span class="token punctuation">)</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>执行一下基准测试：</p>
<pre class="line-numbers language-shell"><code class="language-shell">split $ go test -bench=.
goos: darwin
goarch: amd64
pkg: split
BenchmarkSplit-8                10000000               131 ns/op
BenchmarkSplitParallel-8        50000000                36.1 ns/op
PASS
ok      split       3.308s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>还可以通过在测试命令后添加<code>-cpu</code>参数如<code>go test -bench=. -cpu 1</code>来指定使用的CPU数量。</p>
<h2 id="十一、示例函数"><a href="#十一、示例函数" class="headerlink" title="十一、示例函数"></a>十一、示例函数</h2><p><strong>示例函数的格式</strong></p>
<p>被<code>go test</code>特殊对待的第三种函数就是示例函数，它们的函数名以<code>Example</code>为前缀。它们既没有参数也没有返回值。标准格式如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">ExampleName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">// ...</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>下面的代码是我们为<code>Split</code>函数编写的一个示例函数：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">ExampleSplit</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>split<span class="token punctuation">.</span><span class="token function">Split</span><span class="token punctuation">(</span><span class="token string">"a:b:c"</span><span class="token punctuation">,</span> <span class="token string">":"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    fmt<span class="token punctuation">.</span><span class="token function">Println</span><span class="token punctuation">(</span>split<span class="token punctuation">.</span><span class="token function">Split</span><span class="token punctuation">(</span><span class="token string">"沙河有沙又有河"</span><span class="token punctuation">,</span> <span class="token string">"沙"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true">// Output:</span>
    <span class="token comment" spellcheck="true">// [a b c]</span>
    <span class="token comment" spellcheck="true">// [ 河有 又有河]</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>为你的代码编写示例代码有如下三个用处：</p>
<ol>
<li>示例函数能够作为文档直接使用，例如基于web的godoc中能把示例函数与对应的函数或包相关联。</li>
<li>示例函数只要包含了<code>// Output:</code>也是可以通过<code>go test</code>运行的可执行测试。</li>
</ol>
<pre class="line-numbers language-shell"><code class="language-shell">split $ go test -run Example
PASS
ok      split       0.006s<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<ol start="3">
<li>示例函数提供了可以直接运行的示例代码，可以直接在<code>golang.org</code>的<code>godoc</code>文档服务器上使用<code>Go Playground</code>运行示例代码。下图为<code>strings.ToUpper</code>函数在Playground的示例函数效果。<img src="https://www.liwenzhou.com/images/Go/unit_test/example.png" alt="Go Playground"></li>
</ol>
<h2 id="十二、网络测试"><a href="#十二、网络测试" class="headerlink" title="十二、网络测试"></a>十二、网络测试</h2><h3 id="1-TCP-HTTP"><a href="#1-TCP-HTTP" class="headerlink" title="1. TCP/HTTP"></a>1. TCP/HTTP</h3><p>假设需要测试某个 API 接口的 handler 能够正常工作，例如 helloHandler</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token keyword">func</span> <span class="token function">helloHandler</span><span class="token punctuation">(</span>w http<span class="token punctuation">.</span>ResponseWriter<span class="token punctuation">,</span> r <span class="token operator">*</span>http<span class="token punctuation">.</span>Request<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    w<span class="token punctuation">.</span><span class="token function">Write</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token function">byte</span><span class="token punctuation">(</span><span class="token string">"hello world"</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
<p>那我们可以创建真实的网络连接进行测试：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token comment" spellcheck="true">// test code</span>
<span class="token keyword">import</span> <span class="token punctuation">(</span>
    <span class="token string">"io/ioutil"</span>
    <span class="token string">"net"</span>
    <span class="token string">"net/http"</span>
    <span class="token string">"testing"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">handleError</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">,</span> err <span class="token builtin">error</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    t<span class="token punctuation">.</span><span class="token function">Helper</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token keyword">if</span> err <span class="token operator">!=</span> <span class="token boolean">nil</span> <span class="token punctuation">{</span>
        t<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span><span class="token string">"failed"</span><span class="token punctuation">,</span> err<span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

<span class="token keyword">func</span> <span class="token function">TestConn</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    ln<span class="token punctuation">,</span> err <span class="token operator">:=</span> net<span class="token punctuation">.</span><span class="token function">Listen</span><span class="token punctuation">(</span><span class="token string">"tcp"</span><span class="token punctuation">,</span> <span class="token string">"127.0.0.1:0"</span><span class="token punctuation">)</span>
    <span class="token function">handleError</span><span class="token punctuation">(</span>t<span class="token punctuation">,</span> err<span class="token punctuation">)</span>
    <span class="token keyword">defer</span> ln<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

    http<span class="token punctuation">.</span><span class="token function">HandleFunc</span><span class="token punctuation">(</span><span class="token string">"/hello"</span><span class="token punctuation">,</span> helloHandler<span class="token punctuation">)</span>
    <span class="token keyword">go</span> http<span class="token punctuation">.</span><span class="token function">Serve</span><span class="token punctuation">(</span>ln<span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">)</span>

    resp<span class="token punctuation">,</span> err <span class="token operator">:=</span> http<span class="token punctuation">.</span><span class="token function">Get</span><span class="token punctuation">(</span><span class="token string">"http://"</span> <span class="token operator">+</span> ln<span class="token punctuation">.</span><span class="token function">Addr</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">String</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">"/hello"</span><span class="token punctuation">)</span>
    <span class="token function">handleError</span><span class="token punctuation">(</span>t<span class="token punctuation">,</span> err<span class="token punctuation">)</span>

    <span class="token keyword">defer</span> resp<span class="token punctuation">.</span>Body<span class="token punctuation">.</span><span class="token function">Close</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    body<span class="token punctuation">,</span> err <span class="token operator">:=</span> ioutil<span class="token punctuation">.</span><span class="token function">ReadAll</span><span class="token punctuation">(</span>resp<span class="token punctuation">.</span>Body<span class="token punctuation">)</span>
    <span class="token function">handleError</span><span class="token punctuation">(</span>t<span class="token punctuation">,</span> err<span class="token punctuation">)</span>

    <span class="token keyword">if</span> <span class="token function">string</span><span class="token punctuation">(</span>body<span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token string">"hello world"</span> <span class="token punctuation">{</span>
        t<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span><span class="token string">"expected hello world, but got"</span><span class="token punctuation">,</span> <span class="token function">string</span><span class="token punctuation">(</span>body<span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<ul>
<li><code>net.Listen("tcp", "127.0.0.1:0")</code>：监听一个未被占用的端口，并返回 Listener。</li>
<li>调用 <code>http.Serve(ln, nil)</code> 启动 http 服务。</li>
<li>使用 <code>http.Get</code> 发起一个 Get 请求，检查返回值是否正确。</li>
<li>尽量不对 <code>http</code> 和 <code>net</code> 库使用 mock，这样可以覆盖较为真实的场景。</li>
</ul>
<h3 id="2-httptest"><a href="#2-httptest" class="headerlink" title="2. httptest"></a>2. httptest</h3><p>针对 http 开发的场景，使用标准库 <code>net/http/httptest</code> 进行测试更为高效。</p>
<p>上述的测试用例改写如下：</p>
<pre class="line-numbers language-go"><code class="language-go"><span class="token comment" spellcheck="true">// test code</span>
<span class="token keyword">import</span> <span class="token punctuation">(</span>
    <span class="token string">"io/ioutil"</span>
    <span class="token string">"net/http"</span>
    <span class="token string">"net/http/httptest"</span>
    <span class="token string">"testing"</span>
<span class="token punctuation">)</span>

<span class="token keyword">func</span> <span class="token function">TestConn</span><span class="token punctuation">(</span>t <span class="token operator">*</span>testing<span class="token punctuation">.</span>T<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    req <span class="token operator">:=</span> httptest<span class="token punctuation">.</span><span class="token function">NewRequest</span><span class="token punctuation">(</span><span class="token string">"GET"</span><span class="token punctuation">,</span> <span class="token string">"http://example.com/foo"</span><span class="token punctuation">,</span> <span class="token boolean">nil</span><span class="token punctuation">)</span>
    w <span class="token operator">:=</span> httptest<span class="token punctuation">.</span><span class="token function">NewRecorder</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token function">helloHandler</span><span class="token punctuation">(</span>w<span class="token punctuation">,</span> req<span class="token punctuation">)</span>
    bytes<span class="token punctuation">,</span> <span class="token boolean">_</span> <span class="token operator">:=</span> ioutil<span class="token punctuation">.</span><span class="token function">ReadAll</span><span class="token punctuation">(</span>w<span class="token punctuation">.</span><span class="token function">Result</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span>Body<span class="token punctuation">)</span>

    <span class="token keyword">if</span> <span class="token function">string</span><span class="token punctuation">(</span>bytes<span class="token punctuation">)</span> <span class="token operator">!=</span> <span class="token string">"hello world"</span> <span class="token punctuation">{</span>
        t<span class="token punctuation">.</span><span class="token function">Fatal</span><span class="token punctuation">(</span><span class="token string">"expected hello world, but got"</span><span class="token punctuation">,</span> <span class="token function">string</span><span class="token punctuation">(</span>bytes<span class="token punctuation">)</span><span class="token punctuation">)</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>
<p>使用 httptest 模拟请求对象(req)和响应对象(w)，达到了相同的目的。</p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://zhangyafeii.gitee.io" rel="external nofollow noreferrer">张亚飞</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://zhangyafeii.gitee.io/go/base/di-25-pian-dan-yuan-ce-shi/">https://zhangyafeii.gitee.io/go/base/di-25-pian-dan-yuan-ce-shi/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://zhangyafeii.gitee.io" target="_blank">张亚飞</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Go%E4%B9%8B%E8%B7%AF/">
                                    <span class="chip bg-color">Go之路</span>
                                </a>
                            
                                <a href="/tags/%E5%8D%95%E5%85%83%E6%B5%8B%E8%AF%95/">
                                    <span class="chip bg-color">单元测试</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: 'b9bf0e29501275f4f23c',
        clientSecret: '1c56bc88fdb7b23ee3712916a38e5e8d1311823a',
        repo: 'github.io',
        owner: 'zhangyafeii',
        admin: "zhangyafeii",
        id: '2021-01-08T08-00-00',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/go/stdlib/fmt/">
                    <div class="card-image">
                        
                        <img src="https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Go/blog/fmt.jpg" class="responsive-img" alt="标准库：fmt">
                        
                        <span class="card-title">标准库：fmt</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            fmt标准库是我们在学习Go语言过程中接触最早最频繁的一个了，本文介绍了fmtb包的一些常用函数。
fmt包实现了类似C语言printf和scanf的格式化I/O。主要分为向外输出内容和获取输入内容两大部分。
一、向外输出标准库fmt提供了
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-01-09
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Go/" class="post-category">
                                    Go
                                </a>
                            
                            <a href="/categories/Go/stdlib/" class="post-category">
                                    stdlib
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Go%E4%B9%8B%E8%B7%AF/">
                        <span class="chip bg-color">Go之路</span>
                    </a>
                    
                    <a href="/tags/%E6%A0%87%E5%87%86%E5%BA%93/">
                        <span class="chip bg-color">标准库</span>
                    </a>
                    
                    <a href="/tags/fmt/">
                        <span class="chip bg-color">fmt</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/go/base/di-24-pian-http-bian-cheng/">
                    <div class="card-image">
                        
                        <img src="https://zhangyafei-1258643511.cos.ap-nanjing.myqcloud.com/Go/blog/24.jpg" class="responsive-img" alt="第24篇：http编程">
                        
                        <span class="card-title">第24篇：http编程</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            一、web工作流程
Web服务器的工作原理可以简单地归纳为
客户机通过TCP/IP协议建立到服务器的TCP连接
客户端向服务器发送HTTP协议请求包，请求服务器里的资源文档
服务器向客户机发送HTTP协议应答包，如果请求的资源包含有动态语言
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-01-07
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Go/" class="post-category">
                                    Go
                                </a>
                            
                            <a href="/categories/Go/base/" class="post-category">
                                    base
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Go%E4%B9%8B%E8%B7%AF/">
                        <span class="chip bg-color">Go之路</span>
                    </a>
                    
                    <a href="/tags/%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B/">
                        <span class="chip bg-color">网络编程</span>
                    </a>
                    
                    <a href="/tags/http/">
                        <span class="chip bg-color">http</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 飞凡空间<br />'
            + '文章作者: 张亚飞<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>

    
<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">年份</span>
            <a href="https://zhangyafeii.gitee.io" target="_blank">张亚飞</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">344.5k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    window.setTimeout("siteTime()", 1000);
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2020";
                    var startMonth = "12";
                    var startDate = "18";
                    var startHour = "12";
                    var startMinute = "12";
                    var startSecond = "12";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/zhangyafeii" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="https://gitee.com/zhangyafeii" class="tooltipped" target="_blank" data-tooltip="访问我的Gitee" data-position="top" data-delay="50">
        <i class="fab fa-google-plus"></i>
    </a>



    <a href="mailto:zhangyafeii@foxmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1271570224" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1271570224" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>
    <script src="/js/cursor.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
